package com.wen.controller.system;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wen.common.dto.RoleDTO;
import com.wen.common.utils.ResponseResult;
import com.wen.common.pojo.system.Permission;
import com.wen.common.pojo.system.Role;
import com.wen.system.service.PermissionService;
import com.wen.system.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;


@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;



    @GetMapping("/all")
    public ResponseResult<?> all() {
        return ResponseResult.success(roleService.findAll());
    }

    /**
     *角色分页查询
     */
    @GetMapping("rolePage")
    @RequiresRoles(value = {"admin"})
//    @RequiresPermissions(value = {"add", "delete"})
    public ResponseResult<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "5") Integer pageSize,
                                      @RequestParam(defaultValue = "") String search) {

        Page<RoleDTO> roleDtoPage = roleService.rolePage(pageNum, pageSize, search);
        return ResponseResult.success(roleDtoPage);
    }

    /**
     * 根据角色id查权限菜单
     */
    @GetMapping("/{id}")
    public ResponseResult<?> getById(@PathVariable Long id) {
        return ResponseResult.success(roleService.findPermissionByRoleId(id));
    }

    /**
     * 根据角色id查菜单路由
     */
    @GetMapping("/menuRouter/{id}")
    public ResponseResult<?> getMenuRouter(@PathVariable Long id) {
        List<Permission> permissions = roleService.findPermissionByRoleId(id);
        List<Permission> menuTree = permissionService.getMenuTree(permissions, 0);
        return ResponseResult.success(menuTree);
    }

    /**
     * 改变权限接口
     */
    @PutMapping("/changePermission")
    public ResponseResult<?> changePermission(@RequestBody RoleDTO role) {

//         判断当前登录的用户角色是否包含了当前操作行的角色id，如果包含，则返回true，需要重新登录。

//        如果不包含，则返回false，不需要重新登录。此处都返回false不退出
        return roleService.changePermission(role);
    }

    /**
     * 添加角色addRole
     */
    @PostMapping("/addRole")
    public ResponseResult<?> addRole(@RequestBody Role role) {
        roleService.addRole(role);
        return ResponseResult.success();
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/delRole/{id}")
    public ResponseResult<?> delRole(@PathVariable Long id) {
        roleService.delRole(id);
        return ResponseResult.success();
    }
    @PostMapping("/delRole")
    public ResponseResult<?> delRoleBatch(@RequestBody List<Long> ids) {
        roleService.delRoleBatch(ids);
        return ResponseResult.success();
    }

    /**
     * 编辑角色update
     */
    @PutMapping("/update")
    public ResponseResult<?> update(@RequestBody Role role) {
        roleService.update(role);
        return ResponseResult.success();
    }

    public void creatXlsxFile() throws Exception {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        // 写入数据
//        Row row = sheet.createRow(0);
//        Cell cell = row.createCell(0);
//        cell.setCellValue("Write something");
//        cell = row.createCell(1);
//        cell.setCellValue("Write something else");

//        for (int i = 1; i < 100; i++) {
//
//        }

        workbook.write(new FileOutputStream("C:\\Users\\Devin\\Desktop\\角色信息.xlsx"));
//        fileOutputStream.close();
        workbook.dispose();
    }
    @ApiOperation(value = "导出excel", notes = "导出所有角色的excel表格")
    @PostMapping("/excel")
//    @RequiresPermissions("role:export")
//    @ControllerEndpoint(exceptionMessage = "导出Excel失败",operation = "导出角色excel")
    public ResponseEntity<byte[]> export(HttpServletResponse response) throws Exception {
//        List<Role> roles = this.roleService.findAll();
//        ExcelKit.$Export(Role.class, response).downXlsx(roles, false);
        this.creatXlsxFile();
        File file = new File("C:\\Users\\Devin\\Desktop\\角色信息.xlsx");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment","角色信息.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }



}
